package com.ytzl.itrip.controller;

import com.ytzl.itrip.common.DtoUtil;
import com.ytzl.itrip.common.ErrorCode;
import com.ytzl.itrip.dto.Dto;
import com.ytzl.itrip.service.TokenService;
import com.ytzl.itrip.vo.ItripTokenVO;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;

/**
 * Created by sam on 2018/2/10.
 */
@Controller
@RequestMapping("/api")
public class TokenController extends BaseController {

    @ApiOperation(value = "置换Token", httpMethod = "POST", produces = "application/json", response = Dto.class, notes = "PC端TOKEN过去更换")
    @RequestMapping(value = "/retoken", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public Dto retoken(HttpServletRequest request) {
        String token = request.getHeader("token");
        String userAgent = request.getHeader("user-agent");

        try {
            String newToken = tokenService.replaceToken(userAgent, token);
            ItripTokenVO tokenVO = new ItripTokenVO(newToken, Calendar.getInstance().getTimeInMillis() + TokenService.SESSION_TIMEOUT * 1000, Calendar.getInstance().getTimeInMillis());
            return DtoUtil.returnDataSuccess(tokenVO);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail(e.getMessage(), ErrorCode.AUTH_UNKNOWN);
        }

    }

}
